package com.ruoyi.project.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Random;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.project.system.domain.request.LoginUser;
import com.ruoyi.project.system.domain.request.UpdateUser;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.JwtSignatureValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.domain.User;
import com.ruoyi.project.system.service.IUserService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2020-05-16
 */
@Api("新用户信息管理")
@RestController
@RequestMapping("/app/User")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;
    /**
     * 查询【请填写功能名称】列表
     */
    //@ApiOperation("获取用户列表")
    //@PreAuthorize("@ss.hasPermi('system:User:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:User:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "User");
    }

//    /**
//     * 获取【请填写功能名称】详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('system:User:query')")
//    @GetMapping(value = "/{uid}")
//    public AjaxResult getInfo(@PathVariable("uid") Long uid)
//    {
//        return AjaxResult.success(userService.selectUserById(uid));
//    }

    /**
     * 新增【请填写功能名称】
     */
    //@ApiOperation("添加用户")
    //@PreAuthorize("@ss.hasPermi('system:User:add')")
    @Log(title = "添加用户", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody User user)
    {
        System.out.println(user.getName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增【用户名登录】
     */
    @ApiOperation("用户名登录")
    @Log(title = "用户名登录", businessType = BusinessType.INSERT)
    @PostMapping(value = "/loginUseName")
    public AjaxResult loginUseName(@RequestBody LoginUser user)
    {
        User user1 = new User();
        user1.setName(user.getName());
        user1.setPassword(user.getPassword());
        List<User> users = userService.selectUserList(user1);
        if(users.size() > 0 )
        {
            User userQuery = users.get(0);
            Long uid = userQuery.getUid();
            String token = tokenService.createUserToken(String.valueOf(uid));
            return  AjaxResult.success(token);
        }
        return AjaxResult.error(10001,"用户名不存在！");
    }

    /**
     * 新增【手机号验证码登录】
     */
    @ApiOperation("手机验证码登录")
    @Log(title = "手机验证码登录", businessType = BusinessType.INSERT)
    @PostMapping(value = "/loginSmsCode")
    public AjaxResult loginSmsCode(@RequestParam("phone") String phone ,@RequestParam("code") String code)
    {
        String key = "code-" + phone;
        String cacheCode =  redisCache.getCacheObject(key);
        if(null== cacheCode)
        {
            return AjaxResult.error("请先发送验证码");
        }
        if(!cacheCode.equals(code))
        {
            return AjaxResult.error("验证码错误");
        }
        User user1 = new User();
        user1.setPhone(phone);
        List<User> users = userService.selectUserList(user1);
        if(users.size() > 0 ) {
            User userQuery = users.get(0);
            Long uid = userQuery.getUid();
            String token = tokenService.createUserToken(String.valueOf(uid));
            return  AjaxResult.success(token);
        }else {
            User user = new User(phone);
            userService.insertUser(user);
            Long uid = user.getUid();
            System.out.println("uid="+uid);
            String token = tokenService.createUserToken(String.valueOf(uid));
            return  AjaxResult.success(token);
        }
    }

    /**
     * 新增【请填写功能名称】
     */
    @ApiOperation("获取用户信息")
    @Log(title = "获取用户信息", businessType = BusinessType.OTHER)
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        String uid = tokenService.getUidFromToken(ServletUtils.getRequest());
        if(uid.length() < 1) {
            return AjaxResult.error(10002,"未登录，请授权之后再使用");
        }
        User user = userService.selectUserById(Long.parseLong(uid));
        user.setPassword("");
        return  AjaxResult.success(user);
    }

    /**
     * 新增【请填写功能名称】
     */
    @ApiOperation("获取手机号验证码")
    //@Log(title = "获取手机号验证码", businessType = BusinessType.OTHER)
    @GetMapping("getSmsCode")
    public AjaxResult getSmsCode(@RequestParam("phone") String phone)
    {
        if(phone.length() <11){
            return AjaxResult.error("手机号格式不正确");
        }

        String key = "code-" + phone;
        redisCache.setCacheObject(key ,RandomUtil.randomNumbers(4));
        return  AjaxResult.success(redisCache.getCacheObject(key));
    }


    /**
     * 修改【修改用户信息】
     */
    //@PreAuthorize("@ss.hasPermi('system:User:edit')")
    @ApiOperation("修改用户信息")
    @Log(title = "【修改用户信息】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UpdateUser user)
    {
        String uid = tokenService.getUidFromToken(ServletUtils.getRequest());
        if(uid.length() < 1) {
            return AjaxResult.error(10002,"未登录，请授权之后再使用");
        }
        User newUser = new User();
        newUser.setUid(Long.parseLong(uid));
        newUser.setNick(user.getNick());
        newUser.setAvatar(user.getAvatar());
        newUser.setSex(user.getSex());
        newUser.setSound(user.getSound());
        newUser.setThumb(user.getThumb());
        return toAjax(userService.updateUser(newUser));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:User:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uids}")
    public AjaxResult remove(@PathVariable Long[] uids)
    {
        return toAjax(userService.deleteUserByIds(uids));
    }
}
